package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    // 订单
    @Autowired
    private OrderMapper orderMapper;
    // 订单明细
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    // 收货地址
    @Autowired
    private AddressMapper addressMapper;
    // 获取购物车注入service（之前已完成）
    @Autowired
    private CartService cartService;


    // 用户下单
    @Override
    public void submit(Order order) {
        // 1.获取登录人user对象
        User user = UserHolder.get();
        if (user==null) {
            throw new CustomException("用户未登录，不能下单");
        }
        // 2.查询收货地址对象
        Address address = addressMapper.selectById(order.getAddressId());
        if (address==null) {
            throw new CustomException("收货地址为空，不能下单");
        }
        // 3.获取购物车List集合
        List<Cart> cartList = cartService.findList();
        if (cartList==null&&cartList.size()==0) {
            throw new CustomException("购物车为空，不能下单");
        }

        // 通过mp实现生成雪花id
        Long orderId = IdWorker.getId();

        // 订单总金额
        BigDecimal orderAmount =new BigDecimal(0);
        // 4.遍历购物车集合封装订单明细
        for (Cart cart : cartList) {
            // 封装订单明细
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName()); // 菜品或套餐名称
            orderDetail.setOrderId(orderId);// 订单id
            orderDetail.setDishId(cart.getDishId());// 菜品id
            orderDetail.setSetmealId(cart.getSetmealId());// 套餐id
            orderDetail.setDishFlavor(cart.getDishFlavor()); // 口味
            orderDetail.setNumber(cart.getNumber());// 数量
            orderDetail.setAmount(cart.getAmount()); // 单价
            orderDetail.setImage(cart.getImage());// 图片
            // 调用mapper保存
            orderDetailMapper.insert(orderDetail);

            // 累加订单金额
            // orderAmount = orderAmount+(cart.getAmount()*cart.getNumber())
            orderAmount=orderAmount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }

        // 5.封装订单
        order.setId(orderId); // 订单id
        order.setNumber(orderId.toString()); // 订单号
        order.setStatus(1);// 待付款
        order.setUserId(user.getId()); // 下单用户
        order.setOrderTime(new Date()); // 下单时间
        order.setCheckoutTime(new Date()); // 结账时间
        order.setAmount(orderAmount); // 订单金额
        order.setUserName(user.getName()); // 用户名
        order.setPhone(address.getPhone()); // 收货人手机号
        order.setAddress(address.getDetail()); // 收货地址
        order.setConsignee(address.getConsignee()); // 收货人姓名
        // 6.保存订单
        orderMapper.insert(order);
        // 7.清空购物车
        cartService.clean();
    }


    //分页查询订单详情
    @Override
    public Page<Order> orderByPage(Integer pageNum, Integer pageSize, Long number, String beginTime, String endTime) {
        //构建条件
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.eq(number != null,Order::getId,number);
        qw.between(beginTime !=null && endTime!=null,Order::getOrderTime,beginTime,endTime);

        //创建分页
        Page<Order> page = new Page<>(pageNum,pageSize);

        //查询
        page = orderMapper.selectPage(page, qw);
        return page;
    }


    //历史订单
//历史订单
    @Override
    public Page<Order> lsOrder(Integer pageNum, Integer pageSize) {
        //查询此用户的订单
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.eq(Order::getUserId,UserHolder.get().getId());
        qw.orderByDesc(Order::getOrderTime);//降序,最新订单需求
        //构建分页
        Page<Order> page = new Page<>(pageNum,pageSize);

        //查询
        page = orderMapper.selectPage(page,qw);

        //遍历订单
        for (Order order : page.getRecords()) {
            LambdaQueryWrapper<OrderDetail> oqw = new LambdaQueryWrapper<>();
            oqw.eq(OrderDetail::getOrderId,order.getId());

            List<OrderDetail> orderDetails = orderDetailMapper.selectList(oqw);
            //把每个订单详情放入订单
            order.setOrderDetails(orderDetails);

        }

        //返回数据
        return page;
    }


}